package com.omega.encryptedsql.configuration;

import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.sql.PreparedStatement;

/**
 * @author omega
 * @description: TODO
 * @date 2025/7/12
 */
@Intercepts({
        @Signature(type = ParameterHandler.class,
                method = "setParameters",
                args = {PreparedStatement.class})
})
public class EntityCapturePlugin implements Interceptor {

    private static final ThreadLocal<Object> entityHolder = new ThreadLocal<>();

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        ParameterHandler parameterHandler = (ParameterHandler) invocation.getTarget();

        // 获取参数对象
        Object parameterObject = parameterHandler.getParameterObject();
        entityHolder.set(parameterObject);

        try {
            return invocation.proceed();
        } finally {
            entityHolder.remove();
        }
    }

    public static Object getCurrentEntity() {
        return entityHolder.get();
    }
}

// 注册插件
@Configuration
class MybatisConfig {
    @Bean
    public EntityCapturePlugin entityCapturePlugin() {
        return new EntityCapturePlugin();
    }
}
